<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/19
 * Time: 14:41
 */

namespace app\console\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Url;
use app\index\model\Order;

class Mic extends Controller
{

    /**
     *
     * 提交刷卡支付，并且确认结果，接口比较慢
     * @param WxPayMicroPay $microPayInput
     * @throws WxpayException
     * @return 返回查询接口的结果 微信
     */
    public function w_pay()
    {


        require_once "../extend/w_pay/lib/WxPay.Api.php";
        require_once "../extend/w_pay/example/WxPay.MicroPay.php";
        require_once '../extend/w_pay/example/log.php';

        if ((isset($_REQUEST["auth_code"]) && !preg_match("/^[0-9]{6,64}$/i", $_REQUEST["auth_code"], $matches))) {
            header('HTTP/1.1 404 Not Found');
            exit();
        }
        $paramer = Request::instance()->param();
        $auth_code = $paramer['auth_code'];
        $total_fee = $paramer['price']*100;
        $data['out_trade_no'] = $out_trade_no = $paramer['out_trade_no'];

//初始化日志
        $logHandler = new \CLogFileHandler("./micpay/" . date('Y-m-d') . '.log');
        $log = \Log::Init($logHandler, 15);

        try {
            $input = new \WxPayMicroPay();
            $input->SetAuth_code($auth_code);
            $input->SetBody($out_trade_no);
            $input->SetTotal_fee($total_fee);
            $input->SetOut_trade_no($out_trade_no);
            $microPay = new \MicroPay();
            $result = $microPay->pay($input);
            \Log::ERROR('$return'.json_encode($result));
            if (array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS"){
                \Log::ERROR('start');
                \Log::ERROR('$data[\'out_trade_no\']$data[\'out_trade_no\']'.$data['out_trade_no']);
                $ret = -1;
                $goods_order = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->find();//如果能查到 就是商品类订单
                $order_status = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no']])->value('status');
                $order_type = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no']])->value('order_type');
                \Log::ERROR('$order_type');
                $order_id = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no']])->value('id');
                if ($goods_order && $goods_order['order_type'] == 1) { //商品订单修改订单号
                    \Log::ERROR('order_goods');
                    Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->setField('order_number', $data['out_trade_no']);
                    (new \app\index\controller\Order())->kucun($data['out_trade_no']);
                    $ret = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->update(['status' => 2,'pay_type' => 1,'pay_time' => date('Y-m-d H:i:s',time())]);
                    \Log::ERROR('order_goods_ret'.$ret);
                }
                $gift_order =  Db::name('order')->where(['order_number' => $data['out_trade_no'], 'status' => 1])->find();

                if($gift_order && $gift_order['order_type'] == 3){ //礼包订单 送抽奖次数
                    \Log::ERROR('order_gift');
                    $draw_number = Db::name('draw_number')->where('member_id',$gift_order['member_id'])->find();
                    $number = db('config')->where('varname','web_number')->value('varvalue');
                    //$is_apply = db('config')->where('varname','apply_bool')->value('varvalue');
                    $draw_start = (new \app\draw\controller\Draw())->haha();
                    if($draw_start){
                        $is_apply = 'Y';
                    }else{
                        $is_apply = 'N';
                    }
                    if($is_apply == 'Y') {
                        if (empty($draw_number)) { //第一次插入
                            Db::name('draw_number')->insert(['member_id' => $gift_order['member_id'], 'count' => $number]);
                        } else { //其他情况 相加

                            Db::name('draw_number')->where('member_id', $gift_order['member_id'])->setInc('count', $number);
                        }
                    }
                    $ret = Db::name('order')
                        ->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])
                        ->update([
                            'status' => 6,
                            'pay_type' => 1,
                            'pay_time' => date('Y-m-d H:i:s',time()),
                            'use_time' => date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')+$gift_order['day'],date('Y'))),
                            'mc_start_time' => date('Y-m-d H:i:s',time()),
                            'mc_end_time' => date('Y-m-d H:i:s',time()+3600*24*$gift_order['mc_day']),
                            ]);
                    if($gift_order['t_type'] == 1){ //礼包
                        $order_gift_count = Db::name('order_gift_count')->where('order_id',$gift_order['id'])->select();
                        if(!empty($order_gift_count)){
                            foreach ($order_gift_count as $kogc => $vogc){
                                Db::name('order_gift_count')->where('id',$vogc['id'])->update(['start_time' => date('Y-m-d H:i:s',time()),'end_time' => date('Y-m-d H:i:s',time()+$vogc['day']*3600*24)]);
                            }
                        }
                    }
                    if($gift_order['t_type'] == 2){

                        $member_card_array = [
                            'shop_id' => $gift_order['shop_id'],
                            'member_id' => $gift_order['member_id'],
                            'username' => db('member')->where('id',$gift_order['member_id'])->value('username'),
                            'title' => $gift_order['mc_title'],
                            'content' => $gift_order['mc_content'],
                            'count' => $gift_order['mc_count'],
                            'minus_count' => $gift_order['mc_count'],
                            'start_time' => date('Y-m-d H:i:s',time()),
                            'end_time' => date('Y-m-d H:i:s',time()+3600*24*$gift_order['mc_day']),
                            'type' => $gift_order['mc_type'],
                            'system_card_id' => $gift_order['system_card_id'],
                            'sale_price' => $gift_order['amount'],
                            'origin_price' => 0,
                            'order_id' => $gift_order['id'],
                            'order_number' => $gift_order['order_number'],
                            'single_pic' => $gift_order['mc_single_pic'],
                            'create_time' => date('Y-m-d H:i:s',time())
                        ];
                        Db::name('member_card')->insert($member_card_array);
                        $system_card = Db::name('system_card')->find($gift_order['system_card_id']);
                       // (new \app\index\controller\MemberMessage())->jpushMessage($gift_order['member_id'],'恭喜您获得会员卡('.$system_card['title'].')一张','可用于汽车服务类',3);
                    }

                    \Log::ERROR('order_gift_ret'.$ret);
                }

                if($order_type == 2){ //服务类订单
                    \Log::ERROR('order_service');
                    $find_shop_assignor_records = Db::name('order o')
                        ->join('shop_assignor_records sar','o.id = sar.order_id')
                        ->where('sar.order_id',$order_id)
                        ->find();
                    //Log::DEBUG('$find_shop_assignor_records'.$find_shop_assignor_records);
                    \Log::ERROR('$find_shop_assignor_recordsjson'.json_encode($find_shop_assignor_records));
                    if(!empty($find_shop_assignor_records)){ //有人员
                        \Log::ERROR('$find_shop_assignor_records6');
                        $ret = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->update(['status' => 5,'pay_type' => 1,'pay_time' => date('Y-m-d H:i:s',time())]);
                    }else{
                        \Log::ERROR('$find_shop_assignor_records5');
                        $ret = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->update(['status' => 6,'pay_type' => 1,'pay_time' => date('Y-m-d H:i:s',time())]);
                    }
                    \Log::ERROR('order_service_ret'.$ret);
                }
                Db::name('order')->where('order_number',$data['out_trade_no'])->setField('auth_code',$auth_code);
                (new Order())->salesman($data['out_trade_no']);
               return true;
            }else{
                \Log::ERROR('wofalse');
            }
           // return false;
        } catch (\Exception $e) {
            \Log::ERROR(json_encode(['message' => $e->getMessage(),'line' => $e->getLine()]));
             \Log::ERROR(json_encode($e));
            return false;

        }

    }

    public function a_pay()
    {
        header("Content-type: text/html; charset=utf-8");
        require_once '../extend/a_pay/f2fpay/model/builder/AlipayTradePayContentBuilder.php';
        require_once '../extend/a_pay/f2fpay/service/AlipayTradeService.php';
        $config = require '../extend/a_pay/f2fpay/config/config.php';
            $param = Request::instance()->param();
        //if (!empty($_POST['out_trade_no'])&& trim($_POST['out_trade_no'])!="") {
            // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
            // 需保证商户系统端不能重复，建议通过数据库sequence生成，
            //$outTradeNo = "barpay" . date('Ymdhis') . mt_rand(100, 1000);
        $data['out_trade_no'] = $outTradeNo = $param['out_trade_no'] ;

            // (必填) 订单标题，粗略描述用户的支付目的。如“XX品牌XXX门店消费”
            $subject = $param['subject']='标题';

            // (必填) 订单总金额，单位为元，不能超过1亿元
            // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
            //$totalAmount = $param['total_amount'];
        $totalAmount = $param['price'];

            // (必填) 付款条码，用户支付宝钱包手机app点击“付款”产生的付款条码
            $authCode = $param['auth_code']; //28开头18位数字
            // (可选,根据需要使用) 订单可打折金额，可以配合商家平台配置折扣活动，如果订单部分商品参与打折，可以将部分商品总价填写至此字段，默认全部商品可打折
            // 如果该值未传入,但传入了【订单总金额】,【不可打折金额】 则该值默认为【订单总金额】- 【不可打折金额】
            //String discountableAmount = "1.00"; //

            // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
            // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
            $undiscountableAmount = "0.01";

            // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
            // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
            $sellerId = "";

            // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
            $body = "购买商品2件共15.00元";

            //商户操作员编号，添加此参数可以为商户操作员做销售统计
            $operatorId = "test_operator_id";

            // (可选) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
            $storeId = "test_store_id";

            // 支付宝的店铺编号
            $alipayStoreId = "test_alipay_store_id";

            // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
            $providerId = ""; //系统商pid,作为系统商返佣数据提取的依据
            $extendParams = new \ExtendParams();
            $extendParams->setSysServiceProviderId($providerId);
            $extendParamsArr = $extendParams->getExtendParams();

            // 支付超时，线下扫码交易定义为5分钟
            $timeExpress = "5m";

            // 商品明细列表，需填写购买商品详细信息，
            $goodsDetailList = array();

            // 创建一个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
            $goods1 = new \GoodsDetail();
            $goods1->setGoodsId("good_id001");
            $goods1->setGoodsName("XXX商品1");
            $goods1->setPrice(3000);
            $goods1->setQuantity(1);
            //得到商品1明细数组
            $goods1Arr = $goods1->getGoodsDetail();

            // 继续创建并添加第一条商品信息，用户购买的产品为“xx牙刷”，单价为5.05元，购买了两件
            $goods2 = new \GoodsDetail();
            $goods2->setGoodsId("good_id002");
            $goods2->setGoodsName("XXX商品2");
            $goods2->setPrice(1000);
            $goods2->setQuantity(1);
            //得到商品1明细数组
            $goods2Arr = $goods2->getGoodsDetail();

            $goodsDetailList = array($goods1Arr, $goods2Arr);

            //第三方应用授权令牌,商户授权系统商开发模式下使用
            $appAuthToken = "";//根据真实值填写

            // 创建请求builder，设置请求参数
            $barPayRequestBuilder = new \AlipayTradePayContentBuilder();
            $barPayRequestBuilder->setOutTradeNo($outTradeNo);
            $barPayRequestBuilder->setTotalAmount($totalAmount);
            $barPayRequestBuilder->setAuthCode($authCode);
            $barPayRequestBuilder->setTimeExpress($timeExpress);
            $barPayRequestBuilder->setSubject($subject);
            $barPayRequestBuilder->setBody($body);
            //$barPayRequestBuilder->setUndiscountableAmount($undiscountableAmount);
            $barPayRequestBuilder->setExtendParams($extendParamsArr);
            $barPayRequestBuilder->setGoodsDetailList($goodsDetailList);
            $barPayRequestBuilder->setStoreId($storeId);
            $barPayRequestBuilder->setOperatorId($operatorId);
            //$barPayRequestBuilder->setAlipayStoreId($alipayStoreId);

            $barPayRequestBuilder->setAppAuthToken($appAuthToken);

            // 调用barPay方法获取当面付应答
            $barPay = new \AlipayTradeService($config);
            $barPayResult = $barPay->barPay($barPayRequestBuilder);


        $alipaySevice = new \AlipayTradeService($config);
            switch ($barPayResult->getTradeStatus()) {
                case "SUCCESS":
                    writeLogMic('当面付');
                    Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no']])->setField('auth_code',$authCode);
                        $ret = -1;
                        $order_status = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no']])->value('status');
                        $order_type = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no']])->value('order_type');
                        $order_type = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no']])->value('order_type');
                        $order_id = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no']])->value('id');
                        if($order_status != 1 || $order_status != 6){
                            writeLogMic("return die");
                            // return;
                        }
                    writeLogMic("1231231221");
                    writeLogMic($data['out_trade_no']);
                        $goods_order = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->find();//如果能查到 就是商品类订单

                        if ($goods_order && $goods_order['order_type'] == 1) { //商品订单修改订单号
                            writeLogMic(1);
                            writeLogMic('1');
                            Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->setField('order_number', $data['out_trade_no']);
                            (new \app\index\controller\Order())->kucun($data['out_trade_no']);
                            $ret = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->update(['status' => 2,'pay_type' => 2,'pay_time' => date('Y-m-d H:i:s',time())]);
                        }
                        $gift_order =  Db::name('order')->where(['order_number' => $data['out_trade_no'], 'status' => 1])->find();

                        if($gift_order && $gift_order['order_type'] == 3){ //礼包订单 送抽奖次数
                            writeLogMic(3);
                            $alipaySevice->writeLog(3);
                            $draw_number = Db::name('draw_number')->where('member_id',$gift_order['member_id'])->find();
                            $number = db('config')->where('varname','web_number')->value('varvalue');
                            //$is_apply = db('config')->where('varname','apply_bool')->value('varvalue');
                            $draw_start = (new \app\draw\controller\Draw())->haha();
                            if($draw_start){
                                $is_apply = 'Y';
                            }else{
                                $is_apply = 'N';
                            }
                            if($is_apply == 'Y') {
                                if (empty($draw_number)) { //第一次插入
                                    Db::name('draw_number')->insert(['member_id' => $gift_order['member_id'], 'count' => $number]);
                                } else { //其他情况 相加

                                    Db::name('draw_number')->where('member_id', $gift_order['member_id'])->setInc('count', $number);
                                }
                            }
                            writeLogMic(33);
                            $ret = Db::name('order')
                                ->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])
                                ->update([
                                    'status' => 6,
                                    'pay_type' => 2,
                                    'pay_time' => date('Y-m-d H:i:s',time()),
                                    'use_time' => date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')+$gift_order['day'],date('Y'))),
                                    'mc_start_time' => date('Y-m-d H:i:s',time()),
                                    'mc_end_time' => date('Y-m-d H:i:s',time()+3600*24*$gift_order['mc_day']),
                                ]);
                            if($gift_order['t_type'] == 1){ //礼包
                                $order_gift_count = Db::name('order_gift_count')->where('order_id',$gift_order['id'])->select();
                                if(!empty($order_gift_count)){
                                    foreach ($order_gift_count as $kogc => $vogc){
                                        Db::name('order_gift_count')->where('id',$vogc['id'])->update(['start_time' => date('Y-m-d H:i:s',time()),'end_time' => date('Y-m-d H:i:s',time()+$vogc['day']*3600*24)]);
                                    }
                                }
                            }
                            if($gift_order['t_type'] == 2){
                                $member_card_array = [
                                    'shop_id' => $gift_order['shop_id'],
                                    'member_id' => $gift_order['member_id'],
                                    'username' => db('member')->where('id',$gift_order['member_id'])->value('username'),
                                    'title' => $gift_order['mc_title'],
                                    'content' => $gift_order['mc_content'],
                                    'count' => $gift_order['mc_count'],
                                    'minus_count' => $gift_order['mc_count'],
                                    'start_time' => date('Y-m-d H:i:s',time()),
                                    'end_time' => date('Y-m-d H:i:s',time()+3600*24*$gift_order['mc_day']),
                                    'type' => $gift_order['mc_type'],
                                    'system_card_id' => $gift_order['system_card_id'],
                                    'sale_price' => $gift_order['amount'],
                                    'origin_price' => 0,
                                    'order_id' => $gift_order['id'],
                                    'order_number' => $gift_order['order_number'],
                                    'single_pic' => $gift_order['mc_single_pic'],
                                    'create_time' => date('Y-m-d H:i:s',time())
                                ];
                                Db::name('member_card')->insert($member_card_array);
                                $system_card = Db::name('system_card')->find($gift_order['system_card_id']);
                                //(new \app\index\controller\MemberMessage())->jpushMessage($gift_order['member_id'],'恭喜您获得会员卡('.$system_card['title'].')一张','可用于汽车服务类',3);
                            }
                            writeLogMic(333);
                            writeLogMic($ret);

                        }

                        if($order_type == 2 && $order_status == 1){ //服务类订单
                            writeLogMic(2);
                            $find_shop_assignor_records = Db::name('order o')
                                ->join('shop_assignor_records sar','o.id = sar.order_id')
                                ->where('sar.order_id',$order_id)
                                ->find();
                            //$alipaySevice->writeLog('$find_shop_assignor_records'.$find_shop_assignor_records);
                            writeLogMic('$find_shop_assignor_recordsjson'.json_encode($find_shop_assignor_records));
                            if(!empty($find_shop_assignor_records)){ //已经指派过人员
                                $alipaySevice->writeLog('$find_shop_assignor_records5');
                                $ret = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->update(['status' => 5,'pay_type' => 2,'pay_time' => date('Y-m-d H:i:s',time())]);
                                $alipaySevice->writeLog('$find_shop_assignor_records5ret'.$ret);
                            }else{
                                $alipaySevice->writeLog('$find_shop_assignor_records6');
                                $ret = Db::name('order')->where(['order_number|shop_order_number' => $data['out_trade_no'], 'status' => 1])->update(['status' => 6,'pay_type' => 2,'pay_time' => date('Y-m-d H:i:s',time())]);
                                $alipaySevice->writeLog('$find_shop_assignor_records6ret'.$ret);
                            }

                        }
                    writeLogMic('ret'.$ret);
                    (new Order())->salesman($data['out_trade_no']);

                    writeLogMic('over'.$ret);
                    writeLogMic('over');
                        Db::commit();
                    writeLogMic('====================== 支付宝回调结束：======================');

                    return true;
                    echo "支付宝支付成功:" . "<br>--------------------------<br>";
                    print_r($barPayResult->getResponse());
                    break;
                case "FAILED":
                    return false;
                    echo "支付宝支付失败!!!" . "<br>--------------------------<br>";
                    if (!empty($barPayResult->getResponse())) {
                        print_r($barPayResult->getResponse());
                    }

                    break;
                case "UNKNOWN":
                    echo "系统异常，订单状态未知!!!" . "<br>--------------------------<br>";
                    if (!empty($barPayResult->getResponse())) {
                        print_r($barPayResult->getResponse());
                    }
                    break;
                default:
                    return false;
                    echo "不支持的交易状态，交易返回异常!!!";
                    break;
            }
            return;
        //}
    }
}